package group.igfd.manager.biz.oss;

import com.aliyun.oss.OSSClient;
import group.igfd.manager.biz.utils.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;

@Service
public class UploadServices {


    /**
     * 上传图片资源
     * @param file
     * @return
     */
    public String uploadImgToOSS(File file) {

        OSSClient ossClient=AliyunOSSClient.getOSSClient();
        String url = AliyunOSSClient.uploadObject2OSS(ossClient, file, AliyunOSSClientConstant.BACKET_NAME, AliyunOSSClientConstant.FOLDER);
        ossClient.shutdown();
        return url;
    }

    /**
     * 上传图片资源
     * @param file
     * @return
     */
    public String uploadAIImgSubjectToOSS(File file) {

        OSSClient ossClient=AliyunOSSClient.getOSSClient();
        String url = AliyunOSSClient.uploadObject2OSS(ossClient, file, AliyunOSSClientConstant.BACKET_NAME, AliyunOSSClientConstant.FOLDER_AI_SUBJECE);
        ossClient.shutdown();
        return url;
    }

    /**
     * 上传图片主体 图片资源
     * @param imageBase64
     * @return
     */
    public String uploadAIImgSubjectToOSS(String imageBase64) {

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        File file = null;
        try {
            bytes=decoder.decodeBuffer(imageBase64);
            file = FileUtil.byte2File(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(file)){
            OSSClient ossClient=AliyunOSSClient.getOSSClient();
            String url = AliyunOSSClient.uploadObject2OSS(ossClient, file, AliyunOSSClientConstant.BACKET_NAME, AliyunOSSClientConstant.FOLDER_AI_SUBJECE);
            ossClient.shutdown();
            return url;
        }
        return null;
    }

    /**
     * 上传购买小票
     * @param file
     * @return
     */
    public String uploadInvoiceToOSS(File file) {

        OSSClient ossClient=AliyunOSSClient.getOSSClient();
        String url = AliyunOSSClient.uploadObject2OSS(ossClient, file, AliyunOSSClientConstant.BACKET_NAME_INVOICE, AliyunOSSClientConstant.FOLDER_INVOICE);
        ossClient.shutdown();
        return url;
    }

}
